package com.itheima.Service.Impl;

import com.itheima.Service.CategoryService;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

   /* @Override
    public List<Category> list() {

        //查询所有分类
       List<Category> list = categoryMapper.list();
//找到所有的顶级分类
        List<Category> parents =list.stream().filter(category -> category.getParentId()==0).toList();
        //找到所有非顶级分类
        List<Category> children =list.stream().filter(category -> category.getParentId()>0).toList();

        //递归查找
        parents.forEach(category -> {
            findChildren(category,children);
        });
       return parents;

    }
    *//**
     * 递归查找子分类
     *//*
    public void findChildren(Category category,List<Category> children){
        //创建一个集合,用于存储子分类
        List<Category> currentChildren =new ArrayList<>();
        //循环所有子分类,判断查找当前类的子分类
        List<Category> list = children.stream().filter(c -> Objects.equals(c.getParentId(), category.getId())).toList();
        //如果没有子分类,则结束,有就继续查找(递归查找)
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(c->findChildren(c,children));
        }
        //将查找的结果给当前类的子分类属性children
        category.setChildren(list);

    }*/
    @Override
    public List<Category> list(){
        List<Category> list = categoryMapper.list();
        List<Category> parents = list.stream().filter(c -> c.getParentId() == 0).toList();
        parents.forEach(c->findChildren(c,list));
        return parents;
    }
    /**
     * 递归查找子分类
     */
    public void findChildren(Category parent,List<Category> list){
        List<Category> children = list.stream().filter(c -> Objects.equals(c.getParentId(), parent.getId())).toList();
        parent.setChildren(children);
        children.forEach(c->findChildren(c,list));

    }


}
